#ifndef VIRTUALDEVICECONFIGDIALOG_H
#define VIRTUALDEVICECONFIGDIALOG_H

#include <QDialog>
#include <QJsonObject>
#include <QLineEdit>
#include <QSpinBox>
#include <QCheckBox>
#include <QTableWidget>
#include <QPushButton>
#include "core/DataTypes.h" // For ServerMappingRule

namespace ModbusPlexLink {

class VirtualDeviceConfigDialog : public QDialog {
    Q_OBJECT

public:
    explicit VirtualDeviceConfigDialog(const QJsonObject& config = QJsonObject(), QWidget *parent = nullptr);
    ~VirtualDeviceConfigDialog();

    QJsonObject getConfig() const;

private slots:
    void onAddMapping();
    void onDeleteMapping();
    void onDuplicateMapping();
    void onImportCsv();
    void onExportCsv();
    void onMappingTableSelectionChanged();
    void onMappingTableCellChanged(int row, int column);

    void onAccepted();
    void onRejected();

private:
    void setupUi();
    QWidget* createBasicInfoSection();
    QWidget* createMappingTableSection();

    void loadConfig();
    bool validateConfig();

    void refreshMappingTable();
    void setupMappingTableRow(int row, const ServerMappingRule& rule);
    ServerMappingRule getMappingRuleFromRow(int row) const;
    void updateMappingButtons();

private:
    QJsonObject m_initialConfig;
    QList<ServerMappingRule> m_mappings;
    bool m_isNewDevice;
    bool m_isUpdatingTable;

    // 基本信息 UI
    QLineEdit* m_nameEdit;
    QSpinBox* m_virtualUnitIdSpin;
    QCheckBox* m_enabledCheck;

    // 映射表格 UI
    QTableWidget* m_mappingTable;
    QPushButton* m_addMappingBtn;
    QPushButton* m_deleteMappingBtn;
    QPushButton* m_duplicateMappingBtn;
    QPushButton* m_importCsvBtn;
    QPushButton* m_exportCsvBtn;
};

} // namespace ModbusPlexLink

#endif // VIRTUALDEVICECONFIGDIALOG_H

